import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import './index.scss'
import global from '../../global';
import { Button, Map, Textarea, Input, Image } from '@tarojs/components'
import Request from '../../api/index'
import Utils from '../../utils'
import Event from '../../event';

export default class Index extends Component {

  constructor() {
    super();
    this.state = {
      form: {
        name: '',
        address: '',
        attachment: '',
        representative: '',
        phone: '',
        userId: '',
        serialNumber: '',
      },
      loading: false,
      editable: true
    }
    this.submitForm = this.submitForm.bind(this)
    this.checkAuthStatus = this.checkAuthStatus.bind(this)
  }

  componentWillMount () { }

  componentDidMount () {
    this.checkAuthStatus();
  }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  async checkAuthStatus() {
    if (global.userInfo.companyAuthStatus === '2' || global.userInfo.companyAuthStatus === '1') {
      await Taro.showLoading();
      let res = await Request.get(`/business/wx_company/getByWxUserId/${global.userInfo.userId}`);
      if (res.data.code !== 200) {
        await Taro.hideLoading();
        throw new Error()
      }
      this.setState({
        form: res.data.data,
        editable: false
      });
      await Taro.hideLoading();
    }
  }

  validateForm(form) {

    if (!form.name) {
      Taro.showToast({
        title: '请输入公司名称！',
        icon: "error",
        duration: 1000
      });
      return false;
    }
    if (!form.serialNumber) {
      Taro.showToast({
        title: '请输入统一信用代码！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.address) {
      Taro.showToast({
        title: '请输入公司地址！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.attachment) {
      Taro.showToast({
        title: '请上传营业执照！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.representative) {
      Taro.showToast({
        title: '请输入法定代表人！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.phone) {
      Taro.showToast({
        title: '请输入联系方式！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    return true;
  }

  async submitForm() {
    if (this.state.loading) {
      return;
    }
    this.state.loading = true;
    this.setState({
      loading: true
    })
    let { form } = this.state;
    if (!this.validateForm(form)) {
      this.setState({
        loading: false
      });
      return;
    }
    form.userId = global.userInfo.userId;
    try {
      let res = await Request.post('/business/wx_company/apply', form);
      console.log(res)
      if (res.data.code !== 200) {
        throw new Error();
      }
      await Taro.navigateBack();
      await Taro.showToast({
        title: '提交成功！',
        icon: "success",
        duration: 1000
      });
      Event.emit('backFromBindingPage')
    } catch (e) {
      await Taro.showToast({
        title: '提交失败请重试',
        icon: "error",
        duration: 1000
      })
    } finally {
      this.setState({
        loading: false
      });
    }

  }

  async uploadImg() {
    try {
      let res = await Taro.chooseImage();
      await Taro.showLoading();
      let uploadFileRes = await Taro.uploadFile({
        url: Request.host + '/common/upload',
        filePath: res.tempFilePaths[0],
        name: 'file',
        header: {
          'Authorization': global.token
        },
        success: async (res) => {
          console.log(res, 'sss')
          let data = JSON.parse(res.data)
          if (data.code !== 200) {
            throw new Error();
          }
          this.state.form.attachment = data.fileName;
          this.setState({
            form: this.state.form
          })
          await Taro.hideLoading();
          await Taro.showToast({
            title: '上传成功！',
            type: 'success'
          })
        }
      });
    } catch (e) {
      console.log("上传文件失败")
    } finally {
      await Taro.hideLoading();
    }
  }


  render () {
    let { form, loading, editable} = this.state;

    let msgComponent = <Text className='msg_container color-grey'>填入以下信息进行公司认证</Text>;

    if (global.userInfo.companyAuthStatus === '1') {
      msgComponent = <Text className='msg_container color-blue'>您的认证信息正在审核中</Text>;
    } else if (global.userInfo.companyAuthStatus === '2') {
      msgComponent = <Text className='msg_container color-green'>{global.userInfo.userName}，您已完成公司认证</Text>;
    } else if (global.userInfo.companyAuthStatus === '3') {
      msgComponent = <Text className='msg_container color-yellow'>您的认证信息已被驳回，请重新提交</Text>;
    } else if (global.userInfo.companyAuthStatus === '4') {
      msgComponent = <Text className='msg_container color-red'>您的认证信息已被废弃，请重新提交</Text>;
    }

    return (
      <View className='company_auth_container'>
        <View className='auth_msg_container'>
          {msgComponent}
        </View>
        <View className='input_item'>
          <Text className='required'>公司名称</Text>
          <Input disabled={!editable} value={form.name} onInput={(e) => {this.setState({form: {...form, name: e.detail.value}})}} type='text' placeholder='请输入公司名称'/>
        </View>
        <View className='input_item'>
          <Text className='required'>信用代码</Text>
          <Input disabled={!editable} value={form.serialNumber} onInput={(e) => {this.setState({form: {...form, serialNumber: e.detail.value}})}} type='text' placeholder='请输入统一信用代码'/>
        </View>
        <View className='input_item'>
          <Text className='required'>法定代表</Text>
          <Input disabled={!editable} value={form.representative} onInput={(e) => {this.setState({form: {...form, representative: e.detail.value}})}} type='text' placeholder='请输入法定代表人'/>
        </View>
        <View className='input_item'>
          <Text className='required'>联系方式</Text>
          <Input disabled={!editable} value={form.phone} onInput={(e) => {this.setState({form: {...form, phone: e.detail.value}})}} type='text' placeholder='请输入联系方式'/>
        </View>
        <View className='input_item'>
          <Text className='required'>公司地址</Text>
          <Textarea disabled={!editable} value={form.address} onInput={(e) => {this.setState({form: {...form, address: e.detail.value}})}} type='text' placeholder='请输入公司地址'/>
        </View>
        <View className='input_item'>
          <Text className='required'>营业执照</Text>
          {/*<Input disabled={!editable} value={form.address} onInput={(e) => {this.setState({form: {...form, address: e.detail.value}})}} type='text' placeholder='请输入公司地址'/>*/}
          <View className='img_upload_container'>
            {
              form.attachment ?
                <Image className='image_container' src={Request.imgHost + form.attachment}/>
                :
                <View className='image_container' onClick={this.uploadImg.bind(this)}>
                  <Text className='iconfont icon-add size50 cars_list'/>
                </View>
            }
          </View>
        </View>
        {
          editable && <Button loading={loading} className='submit_btn' type='primary' onClick={this.submitForm}>提交</Button>
        }
        {
          editable && <View className='tips'>
            <Text className='iconfont icon-tanhao size40'/>
            <Text className='size28'> 提交申请后，我们尽快进行核实</Text>
          </View>
        }
      </View>
    )
  }
}
